package com.amc.framework.filter;

import com.amc.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author ZhangXX
 * @date @2021/10/15 17:11
 */
@WebFilter(filterName = "repeatableFilter", urlPatterns = "/*")
public class RepeatableFilter implements Filter {

    @Value("${print.requestLog:false}")
    private Boolean printRequestLog;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        if (!printRequestLog) {
            chain.doFilter(request, response);
        }

        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest && StringUtils.equalsAnyIgnoreCase(request.getContentType(),
                MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE)) {
            try {
                requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (null == requestWrapper) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void destroy() {
    }

}
